iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0

一、在 Dify 先建立 AI 聊天助手

1. 建立應用與設定 Prompt

  1. 登入 Dify 平台。
  2. 點左上角 新建應用程式 (Create App) 選擇 聊天助手 (Chatbot)
  3. 輸入名稱(例:n8n 鐵人賽助手) 點 建立
  4. 在左側選單 提示詞 (Prompt) 設定頁,設定 AI 的人設。
    https://ithelp.ithome.com.tw/upload/images/20251006/20169078U7N6kiL8Ng.png

2. 獲取 API 金鑰

  1. 在左側選單 訪問API
  2. 點 右上角API 金鑰建立金鑰,複製這組金鑰(這就是後面 n8n 呼叫 Dify 服務的 Authorization 憑證)。
    https://ithelp.ithome.com.tw/upload/images/20251006/20169078aBj6eVdhXi.png

二、在 n8n 建立串接流程

1. Webhook 節點 (接收請求)

  1. 新增 Webhook 節點。
  2. 設定:
    • HTTP MethodPOST
    • Pathdify-test
    • Authentication:None
    • RespondUsing 'Respond to Webhook' Node (確保 AI 回覆後才回傳)
    • (測試網址:http://localhost:5678/webhook-test/dify-test)
      https://ithelp.ithome.com.tw/upload/images/20251006/20169078iPch7pAGlB.png

2. HTTP Request 節點 (呼叫 Dify API)

  1. 新增 HTTP Request 節點,連接在 Webhook 後面。
  2. 設定:
    • MethodPOST
    • URLhttps://api.dify.ai/v1/chat-messages
    • Authentication:None
    • Send Headers
      • Header Parameters:
        • Authorization = Bearer 你的Dify API金鑰
          https://ithelp.ithome.com.tw/upload/images/20251006/20169078juvGmg9aiq.png
    • Body Content TypeJSON
    • JSON Body
      {
        "inputs": {}, 
        "query": "{{$json['body']['message']}}", 
        "response_mode": "blocking",
        "user": "api-user"
      }
      

3. Set 節點 (抽取 AI 回覆)

  1. 新增 Set 節點。
  2. 設定:
    • ModeJSON
    • Fields to Set點擊Add Field
      • reply 選擇 String(字串)=={{$json["answer"]}}
        https://ithelp.ithome.com.tw/upload/images/20251006/20169078PaApiZ17ka.png

4. Respond to Webhook 節點 (回傳結果)

  1. 新增 Respond to Webhook 節點。
  2. 設定:
    • Respond WithFirst Incoming Item (會把 Set 節點輸出的 JSON {"reply":"..."} 回傳給呼叫者)。
      https://ithelp.ithome.com.tw/upload/images/20251006/20169078LdxFEOqNDH.png

三、啟用 Workflow 與 PowerShell 測試

1. 啟用 Workflow

2. PowerShell 測試 (帶 UTF-8 編碼)

啟用 Workflow 後,使用 PowerShell 執行 POST 請求,將帶有中文的 JSON ({"message": "今天天氣怎樣"}) 傳給 Webhook。

powershell

$json = '{"message":"今天天氣怎樣"}' 
Invoke-RestMethod -Uri "http://localhost:5678/webhook-test/dify-test" `
  -Method POST `
  -Headers @{ "Content-Type" = "application/json; charset=utf-8" } `
  -Body ([System.Text.Encoding]::UTF8.GetBytes($json))

https://ithelp.ithome.com.tw/upload/images/20251006/201690783seuz4HWvU.png
HTTP Resquest 運轉畫面:
https://ithelp.ithome.com.tw/upload/images/20251006/20169078lvTu8QWiwH.png
n8n Output畫面:
https://ithelp.ithome.com.tw/upload/images/20251006/20169078pCb7WM3mxt.png


上一篇
Day 15 : API 串接失敗學習紀錄
下一篇
Day 17 : 用 n8n 自動回覆訊息(Webhook 接 API)
系列文
從零開始 : 學習運用 n8n 與 Dify 的 AI 自動化實戰25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言